/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package cryptoutil

import (
	"encoding/pem"

	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/core"
	factory "git.cloud.inspur.com/ichain/ichain-sdk-go/thirdparty/ca/sdk/cryptosuitebridge"
	"github.com/pkg/errors"
	x509GM "github.com/tjfoc/gmsm/x509"
)

// GetPublicKeyFromCert 在证书中获取公钥
func GetPublicKeyFromCert(cert []byte, cs core.CryptoSuite) (core.Key, error) {
	dcert, _ := pem.Decode(cert)
	if dcert == nil {
		return nil, errors.Errorf("Unable to decode cert bytes [%v]", cert)
	}
	x509Cert, err := x509GM.ParseCertificate(dcert.Bytes)
	key, err := cs.KeyImport(x509Cert.PublicKey, factory.GetX509PublicKeyImportOpts(true))
	if err != nil {
		return nil, errors.WithMessage(err, "Failed to import certificate's public key")
	}

	return key, nil
}
